import React,{useEffect,useState} from "react";
import axios from "axios";
import PubSub from "pubsub-js";
import {Empty} from "antd-mobile";
import PopularityItem from "../../Frontpage/Popularity/PopularityItem";
import Loading from "../../../Loading";
import { Ivegetable } from "../../Frontpage/SpecialOffer";
import {typeOfFood} from "../Nav";
import style from './index.module.css'
const {content} = style

export default function MainContent(){

    const [isLoading,setIsLoading] = useState(true)

    const [vegetable,setVegetable] = useState<Ivegetable[]>()

    async function getVag(value:string){
        setIsLoading(true)
        const result = await axios.get(`/api/vegetableClassification?type=${value}&limit=0`)
        setVegetable(result.data)
        setIsLoading(false)
    }


    useEffect(() => {
        getVag(typeOfFood[0])

        const veg = PubSub.subscribe('typeOfFood',(message,data:string)=>{
            getVag(data)
        })
        return ()=>{
            PubSub.unsubscribe(veg)
        }

    }, [])

    function render(){
        if (!vegetable?.length) return <Empty description='暂无数据' imageStyle={{ width: 128 }}/>
        return vegetable?.map(item=>{
            return (
                <PopularityItem {...item} key={item._id}/>
            )
        })

    }

    return (
        <ul className={content}>
            {
                //TODO:空空如也的界面和失败的界面
                isLoading ?
                    <Loading/>
                    :
                    render()
            }
        </ul>
    )
}